import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/store/user'
import { useWhiteListStore } from '@/store/whiteList'
// 引入基础白名单
import baseWhiteList from '@/sso/baseWhiltList'
import example from './example'
import login from './login'
import exception from './exception'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/home',
    name: 'globalLayout',
    component: () => import(/* webpackChunkName: "globalLayout" */ '../components/layout/GlobalLayout.vue'),
    children: [
      {
        path: 'home',
        name: 'home',
        meta: {
          title: '首页',
          keepAlive: true
        },
        component: () => import(/* webpackChunkName: "home" */ '../views/Home.vue')
      },
      ...example,
    ]
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  },
  ...login,
  ...exception,
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404',
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  const store = useUserStore()
  const whiteListStore = useWhiteListStore()

  // 如果是在基础白名单中就让跳转
  if (baseWhiteList.includes(to.name as string)) {
    next()
  } else {
    // 否则看一下是不是登录了
    const user = store.user
    // 没有登录去登录页面
    if (!user) {
      if (to.name !== 'login') {
        next({ name: 'login' })
      } else {
        next()
      }
    } else {
      const menuWhiteList = whiteListStore.whiteList
      // 基础白名单加角色有权访问的菜单
      const whiteList = baseWhiteList.concat(menuWhiteList)
      // 如果访问的路由没有在白名单里就去403
      if (!whiteList.includes(to.name as string)) {
        next({ name: '404' })
      } else {
        next()
      }
    }
  }
})

export default router
